import React from 'react'
import {Col, Row,Select,Checkbox,Tree,Button} from "antd";
const { TreeNode } = Tree;
import {
    WeaLocaleProvider,
    WeaInput,
    WeaBrowser,
    WeaFormItem,
    WeaInputNumber,
    WeaSearchGroup,
    WeaSelect,
    WeaTools,
    WeaCheckbox
} from "ecCom";
import EField_New from "../../../portal/elements/components/common/setting_new/content/base/EField_New";
import EOrderCol from "../../../portal/elements/components/common/setting_new/content/base/EOrderCol";
const getLabel = WeaLocaleProvider.getLabel;

export default class AddExtends extends React.Component{

    state = {
        showFieldComponentVisible:false,
        orderFieldComponentVisible:false,
        treeLoading: false,
        treeData: []
    }

    componentWillMount(){
        const {setSetting,setId,setting} = this.props
        const {isExcluded=2,needNode=false} = setting
        if(setId == -1){
            setSetting({
                viewType : '1',
                showCopy : '1',
                showForward : '1',
                showReject : '1',
                showCy : '1',
                showTimeout : '0',
                isArrangement : '0',
                completeflag : '0',
                showNoReply : '1',
                flowCount : '0',
                rollingDirection : '0',
                isExcluded : '2',
                isExclude : '2',
                expandedKeys : [],
                checkedKeys : {checked:[],halfChecked:[]},
                selectedKeys : [],
                needNode : false,
                typeids : [],
                flowids : [],
                nodeids : [],
                orderby : '',
                orderDA : '',

            })
        }

        this.getTreeData(isExcluded,needNode)
    }



    render(){
        const {treeData} = this.state
        const {data,setting,setSetting} = this.props
        let {sourceTypes=[],showFields=[],orderFields=[]} = data
        if(setting.orderFields){
            orderFields = setting.orderFields
        }
        const {showField=[],orderField=[],viewType,showCopy,showForward,showReject,showCy,showTimeout,isArrangement,completeflag,showNoReply,flowCount,rollingDirection,isExclude,isExcluded,expandedKeys=[],checkedKeys=[],selectedKeys=[],needNode,typeids=[],flowids=[],nodeids=[],orderby} = setting

        const completeflags = [{
            key: "0",
            selected: true,
            showname: getLabel(235, "所有"),
        },{
            key: "1",
            selected: false,
            showname: getLabel(732, "未完成"),
        },{
            key: "2",
            selected: false,
            showname: 	getLabel(1961, "已完成"),
        }]

        let flowCounts = [{
            key: "0",
            selected: true,
            showname: getLabel(23857, "不显示"),
        },{
            key: "1",
            selected: false,
            showname: getLabel(82641, "显示未读数"),
        },{
            key: "2",
            selected: false,
            showname: getLabel(20234, "显示全部"),
        }]

        if(viewType == 2 || viewType == 3 || viewType == 4 || viewType == 10){
            flowCounts = [{
                key: "0",
                selected: true,
                showname: getLabel(23857, "不显示"),
            },{
                key: "1",
                selected: false,
                showname: getLabel(82641, "显示未读数"),
            }]
        }

        if(viewType == 13 || viewType == 14) {
            flowCounts = [{
                key: "0",
                selected: true,
                showname: getLabel(23857, "不显示"),
            },{
                key: "2",
                selected: false,
                showname: getLabel(20234, "显示全部"),
            }]
        }

        const rollingDirections = [{
            key: "0",
            selected: true,
            showname: getLabel(	511807, "无"),
        },{
            key: "1",
            selected: false,
            showname: getLabel(	22986, "左"),
        },{
            key: "2",
            selected: false,
            showname: getLabel(	22988, "右"),
        },{
            key: "3",
            selected: false,
            showname:  getLabel(23009, "上"),
        },{
            key: "4",
            selected: false,
            showname: getLabel(23010, "下"),
        }]

        const sourceWays = [{
            key: "2",
            selected: false,
            showname: getLabel(	332, "全部"),
        },{
            key: "0",
            selected: false,
            showname: getLabel(	385227, "选择路径"),
        },{
            key: "1",
            selected: false,
            showname: getLabel(	508238, "排除路径"),
        },{
            key: "3",
            selected: false,
            showname: getLabel(	391136, "选择类型"),
        },{
            key: "4",
            selected: false,
            showname: getLabel(	508239, "排除类型"),
        }]

        let showFieldComponent = <div></div>
        const {showFieldComponentVisible} = this.state
        if (showFieldComponentVisible) {
            const eFieldNewProps = {
                eFieldNewDataSource: _.cloneDeep(showFields),
                eFieldNewUsedKeys: _.cloneDeep(showField),
                onOk: (data) => {
                    setSetting({
                        /* eFieldNewDataSource: _.cloneDeep(data.eFieldNewDataSource),*/
                        showField: _.cloneDeep(data.eFieldNewUsedKeys),

                    });
                    this.setState(function(state,props){
                        return {
                            showFieldComponentVisible:false
                        }
                    })
                },
                onCancel: () => {
                    this.setState({
                        showFieldComponentVisible: false
                    });
                }
            };
            showFieldComponent = <EField_New ecId={`${this && this.props && this.props.ecId || ''}_EField_New@xid0tb`} {...eFieldNewProps}/>
        }
        const showFieldSelectedNames = [];
        for (let i = 0; i < showField.length; i++) {
            for (let j = 0 ; j < showFields.length; j++) {
                if (showField[i] == showFields[j].key) {
                    showFieldSelectedNames.push(showFields[j].name);
                }
            }
        }

        let orderFieldComponent = <div></div>
        const {orderFieldComponentVisible} = this.state

        if (orderFieldComponentVisible) {
            const orderColProps = {
                orderColDataSource: _.cloneDeep(orderFields),
                orderColUsedKeys: _.cloneDeep(orderField),
                onOk: (data) => {
                    let orderby = ""
                    let orderDA = ""
                    for(let i= 0; i< data.orderColUsedKeys.length ;i++){
                        for(let j= 0; j< data.orderColDataSource.length ;j++){
                            if(data.orderColUsedKeys[i] == data.orderColDataSource[j].id){
                                orderby += ","+data.orderColDataSource[j].fieldColumn
                                orderDA += ","+data.orderColDataSource[j].orderType
                                break
                            }
                        }
                    }
                    if(orderby != ""){
                        orderby = orderby.slice(1)
                    }
                    if(orderDA != ""){
                        orderDA = orderDA.slice(1)
                    }
                    setSetting({
                        orderFields: _.cloneDeep(data.orderColDataSource),
                        orderField: _.cloneDeep(data.orderColUsedKeys),
                        orderby,
                        orderDA
                    });
                    this.setState(function(state,props){
                        return {
                            orderFieldComponentVisible:false
                        }
                    })
                },
                onCancel: () => {
                    this.setState({
                        orderFieldComponentVisible: false
                    });
                }
            };
            orderFieldComponent = <EOrderCol ecId={`${this && this.props && this.props.ecId || ''}_EOrderCol@k7q0tz`} {...orderColProps}/>
        }
        const orderFieldSelectedNames = [];
        for (let i = 0; i < orderField.length; i++) {
            for (let j = 0; j < orderFields.length; j++) {
                if (orderField[i] == orderFields[j].key) {
                    orderFieldSelectedNames.push(orderFields[j].fieldName+ '-' + (orderFields[j].orderType == '0' ? getLabel(340,'降序') : getLabel(339,'升序')));
                }
            }
        }





        return (
            <div className="workflow-addExtend">
                <div style={{'margin-top':'10px'}}>
                    <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@6vpxes`} type="flex" align="middle">
                        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@zk7pzd`} span={6} >
                            <div>{getLabel(17483, '查看类型')} :</div>
                        </Col>
                        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@rdqh2l`} span={18}>
                            <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@vraudq`}
                                options={sourceTypes}
                                value={viewType}
                                onChange={(value)=>{
                                    setSetting({
                                        viewType: value,
                                    });
                                }}
                            />
                        </Col>
                    </Row>
                </div>

                <div>
                    <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@sky3d2`} type="flex" align="middle">
                        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@lx8ntf`} span={6} >
                        </Col>
                        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@v3uoq1`} span={18}>
                            {
                                viewType == '1' ? (
                                    <div>
                                        <div className="first-items">
                                            <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@ibofmd`}
                                                value={showCopy}
                                                onChange={(value) => {
                                                    setSetting({
                                                        showCopy: value,
                                                    });
                                                }}
                                            />
                                            <span className="nameSpaceing">{getLabel(386553, '显示抄送事宜')}</span>

                                            <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@au2a8k`}
                                                value={showForward}
                                                onChange={(value) => {
                                                    setSetting({
                                                        showForward: value,
                                                    });
                                                }}
                                            />
                                            <span className="nameSpaceing">{getLabel(503867, '显示转发事宜')}</span>
                                            <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@t1dinn`}
                                                value={showReject}
                                                onChange={(value) => {
                                                    setSetting({
                                                        showReject: value,
                                                    });
                                                }}
                                            />
                                            <span className="nameSpaceing">{getLabel(390270, '显示退回事宜')}</span>
                                        </div>
                                        <div className="second-items">
                                            <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@bf3d2j`}
                                                value={showCy}
                                                onChange={(value) => {
                                                    setSetting({
                                                        showCy: value,
                                                    });
                                                }}
                                            />
                                            <span className="nameSpaceing">{getLabel(504692, '显示传阅事宜')}</span>

                                            <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@o781yn`}
                                                value={showTimeout}
                                                onChange={(value) => {
                                                    setSetting({
                                                        showTimeout: value,
                                                    });
                                                }}
                                            />
                                            <span className="nameSpaceing">{getLabel(126834, '优先显示超时流程')}</span>
                                        </div>
                                    </div>
                                ) : null
                            }

                            {
                                viewType == '2' ? (
                                    <div className="first-items">
                                        <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@063yu3`}
                                            value={isArrangement}
                                            onChange={(value) => {
                                                setSetting({
                                                    isArrangement: value,
                                                });
                                            }}
                                        />
                                        <span className="nameSpaceing">{getLabel(386554, '显示办结事宜')}</span>
                                    </div>
                                ) : null
                            }

                            {
                                viewType == '4' ? (
                                    <div className="first-items">
                                        <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@5fmksc`}
                                            options={completeflags}
                                            value={completeflag}
                                            onChange={(value)=>{
                                                setSetting({
                                                    completeflag: value,
                                                });
                                            }}
                                        />
                                    </div>
                                ) : null
                            }

                            {
                                viewType == '13' ? (
                                    <div className="first-items">
                                        <WeaCheckbox ecId={`${this && this.props && this.props.ecId || ''}_WeaCheckbox@hof2jg`}
                                            value={showNoReply}
                                            onChange={(value) => {
                                                setSetting({
                                                    showNoReply: value,
                                                });
                                            }}
                                        />
                                        <span className="nameSpaceing">{getLabel(503437, '仅显示有传阅接收人未批示的流程')}</span>
                                    </div>
                                ) : null
                            }
                        </Col>
                    </Row>
                </div>

                {
                    !(viewType == 6 || viewType == 8) ? (
                        <div style={{'margin-top':'10px'}}>
                            <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@crssam`} type="flex" align="middle">
                                <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@ya1yoi`} span={6} >
                                    <div>{getLabel(390629, '显示数量')} :</div>
                                </Col>
                                <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@ehxcr3`} span={18}>
                                    <div>
                                        <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@1mw3jz`}
                                            options={flowCounts}
                                            value={flowCount}
                                            detailtype={3}
                                            onChange={(v,showname)=>{
                                                setSetting({flowCount:v})
                                            }}
                                        />
                                    </div>
                                </Col>
                            </Row>
                        </div>
                    ) : null
                }


                <div style={{'margin-top':'10px'}}>
                    <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@sejci9`} type="flex" align="middle">
                        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@d207g5`} span={6} >
                            <div>{getLabel(19495, '显示字段')} :</div>
                        </Col>
                        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@xe5rbf`} span={18}>
                            {showFieldComponent}
                            <div style={{height: '100%', lineHeight: '23px'}}>
                                <i className="icon-coms-Flow-setting portal-esetting-btn"
                                   style={{position: "relative", zIndex: "12",top:5}}
                                   onClick={() => this.setState({showFieldComponentVisible: true})}/>
                                <div
                                    title={showFieldSelectedNames.join('，')} style={{marginTop:-18,"-webkit-line-clamp": 2,
                                    "-webkit-box-orient": "vertical",    "cursor": "pointer"}}>&nbsp;&nbsp;&nbsp;&nbsp;{showFieldSelectedNames.join('，')}</div>
                            </div>

                        </Col>
                    </Row>
                </div>

                <div style={{'margin-top':'10px'}}>
                    <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@o2dh4w`} type="flex" align="middle">
                        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@jinous`} span={6} >
                            <div>{getLabel(15512, '排序字段')} :</div>
                        </Col>
                        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@fjdirn`} span={18}>
                            {orderFieldComponent}
                            <div style={{height: '100%', lineHeight: '23px'}}>
                                <i className="icon-coms-Flow-setting portal-esetting-btn"
                                   style={{position: "relative", zIndex: "12",top:5}}
                                   onClick={() => this.setState({orderFieldComponentVisible: true})}/>
                                <div
                                    title={orderFieldSelectedNames.join('，')} style={{marginTop:-18,"-webkit-line-clamp": 2,
                                    "-webkit-box-orient": "vertical",    "cursor": "pointer"}}>&nbsp;&nbsp;&nbsp;&nbsp;{orderFieldSelectedNames.join('，')}</div>
                            </div>

                        </Col>
                    </Row>
                </div>

                <div style={{'margin-top':'10px'}}>
                    <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@2uyfqd`} type="flex" align="middle">
                        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@4cb5kq`} span={6} >
                            <div>{getLabel(20281, '滚动方向')} :</div>
                        </Col>
                        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@f0nlyw`} span={18}>
                            <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@0y1ht8`}
                                options={rollingDirections}
                                value={rollingDirection}
                                onChange={(v,showname)=>{
                                    setSetting({rollingDirection:v})
                                }}
                            />
                        </Col>
                    </Row>
                </div>

                <div style={{'margin-top':'10px'}}>
                    <Row ecId={`${this && this.props && this.props.ecId || ''}_Row@omzvnv`} type="flex" align="middle">
                        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@m2qd9t`} span={6} >
                            <div>{getLabel(21672, '流程来源')} :</div>
                        </Col>
                        <Col ecId={`${this && this.props && this.props.ecId || ''}_Col@0i0uka`} span={18}>
                           <div>
                               <div>
                                   <WeaSelect ecId={`${this && this.props && this.props.ecId || ''}_WeaSelect@5ymwzo`}
                                       options={sourceWays}
                                       value={isExcluded}
                                       onChange={value => {
                                           // setSetting({isExcluded: value})
                                           if(value == '2'){
                                               setSetting({isExclude: 2,isExcluded:value,expandedKeys:[],checkedKeys : {checked:[],halfChecked:[]},typeids:[],flowids:[],nodeids:[]})
                                           }else if(value == '0' || value == '3'){
                                               setSetting({isExclude: 0,isExcluded:value,expandedKeys:[],checkedKeys : {checked:[],halfChecked:[]},typeids:[],flowids:[],nodeids:[]})
                                           }else if(value == '1' || value == '4'){
                                               setSetting({isExclude: 1,isExcluded:value,expandedKeys:[],checkedKeys : {checked:[],halfChecked:[]},typeids:[],flowids:[],nodeids:[]})
                                           }
                                            this.getTreeData(value, needNode)


                                       }}
                                   />
                               </div>
                               <div style={{position:'relative'}}>
                                   {
                                       (isExcluded == '0' || isExcluded =='1') ? (
                                           <div style={{position: 'absolute', top: '10px', right: '20px'}}>
                                               <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@qt1gna`} size="small" title={needNode ? getLabel(386556, '包含节点') : getLabel(386557, '不包含节点')} onClick={() => {setSetting({needNode:!needNode});this.getTreeData(isExcluded,!needNode)}}>
                                                   <i className={needNode ? 'icon-coms-DisplaySubordinates' : 'icon-coms-NoDisplayOfSubordinates'} style={{color: needNode ? 'rgb(45, 183, 245)' : ''}}/>
                                               </Button>
                                           </div>
                                       ) : null

                                   }
                                   {
                                       isExcluded != '2' ? (
                                           <Tree ecId={`${this && this.props && this.props.ecId || ''}_Tree@3b19hv`}
                                               checkable
                                               checkStrictly={true}
                                               expandedKeys={expandedKeys}
                                               onExpand={this.onExpand}
                                               checkedKeys={checkedKeys}
                                               onCheck={this.onCheck}
                                               // selectedKeys={selectedKeys}
                                               // onSelect={this.onSelect}
                                               loadData={this.asyncGetTreeDataOfPid}
                                           >
                                               {this.getTreeNodes(treeData)}

                                           </Tree>
                                       ) : null
                                   }

                               </div>
                           </div>
                        </Col>
                    </Row>
                </div>
            </div>
        )
    }


    asyncGetTreeDataOfPid = (node, isInit)=>{
        const {id} = node.props;

        if (!isInit) {
            this.setState({treeLoading: true});
        }

        WeaTools.callApi('/api/public/browser/data/-99991', 'GET', {
            isWfTree: 1,
            needNode: 1,
            type: 'wf',
            id: id
        }).then(data => {
            const loop = (treeData, pid, data) => {
                for (let i = 0, len = treeData.length; i < len; i++) {
                    if (treeData[i].id == pid && treeData[i].type == 'wf') {
                        treeData[i].subs = data || [];
                        break;
                    } else {
                        const children = treeData[i].subs;
                        if (children && children.length) {
                            loop(children, pid, data);
                        }
                    }
                }
            };

            const {treeData} = this.state;
            const {setting,setSetting} = this.props
            const {expandedKeys} = setting

            loop(treeData, id, data.datas);
            this.setState({treeLoading: false, treeData: treeData});
            setSetting({expandedKeys:[...expandedKeys, 'wf_' + id]})
        });
    }

    getTreeData = (isExcluded, needNode)=>{
        const {setting} = this.props
        const {viewType,flowids} = setting

        if(isExcluded != 2){
            let api = ''
            if(isExcluded == '3' || isExcluded == '4'){
                api = '/api/portal/workFlowType/getWorkFlowTypeDatas';
            }else if(isExcluded =='0' || isExcluded =='1'){
                api = '/api/public/browser/data/-99991'
            }
            WeaTools.callApi(api, 'GET', {
                isWfTree: 1,
                needNode:  needNode ? 1 : 0 ,
                containsOfs: 1,
                viewtype: viewType
            }).then(data => {
                if(isExcluded == '3' || isExcluded =='4') {
                    this.setState({treeLoading: false, treeData: data.wfType.datas});
                }else if(isExcluded =='0' || isExcluded =='1'){
                    this.setState({treeLoading: false, treeData: data.datas.subs});
                }

                if (needNode && isExcluded != '3' && isExcluded =='4') {
                    const flowidarr = flowids.split(',');
                    if (flowidarr && flowidarr.length) {
                        for (let i = 0, len = flowidarr.length; i < len; i++) {
                            this.asyncGetTreeDataOfPid({props: {id: flowidarr[i]}}, true);
                        }
                    }
                }
            });
        }


    }

    getTreeNodes(treeData) {
        const loop = (data, pids) => {
            return data.map((item) => {
                const _pids = _.cloneDeep(pids);
                _pids.push(item.type + '_' + item.id);

                const children = item.subs;
                if (children && children.length) {
                    return <TreeNode ecId={`${this && this.props && this.props.ecId || ''}_TreeNode@b523tz@${item.id}`} key={item.type + '_' + item.id} id={item.id} pids={_pids} title={item.name} isLeaf={!item.isParent}>{loop(children, _pids)}</TreeNode>;
                } else {
                    return <TreeNode ecId={`${this && this.props && this.props.ecId || ''}_TreeNode@w8l9ph@${item.id}`} key={item.type + '_' + item.id} id={item.id} pids={_pids} title={item.name} isLeaf={!item.isParent}/>;
                }
            });
        };

        return loop(treeData, []);
    }

    onExpand = (expandedKeys)=>{
        const {setSetting} = this.props
        setSetting({expandedKeys: expandedKeys});
    }

    onCheck = (checkedKeys, e)=>{
        const {setSetting} = this.props
        const {eventKey, pids, children = []} = e.node.props;
        const childrenKeys = this.getChildrenKeys(children);
        let grandSonKey = '';
        children.map(item => {
            if(item.props.children){
                let itemChildren = this.getChildrenKeys(item.props.children);
                if(itemChildren) {
                    grandSonKey = grandSonKey + ',' +itemChildren;
                };
            };
        })
        let grandSonKeys = grandSonKey.split(',');
        let checked = [];
        if (e.checked) {
            checked = _.concat(...pids, ...childrenKeys, ...grandSonKeys, checkedKeys.checked);
            // checked = _.concat(...pids, ...childrenKeys, ...grandSonKeys, checkedKeys);
        } else {
            checked = _.pullAll(checkedKeys.checked, _.concat(childrenKeys,grandSonKeys));
            // checked = _.pullAll(checkedKeys, _.concat(childrenKeys,grandSonKeys));
        }
        const _checked = _.uniq(checked);

        const {isShowNodeBtn, isNeedNode} = this.state;

        let typeids = [], flowids = [], nodeids = [];
        for (let i = 0, len = _checked.length; i < len; i++) {
            const _keys = _checked[i].split('_');
            if (_keys[0] == 'wftype') {
                typeids.push(_keys[1])
            } else if (_keys[0] == 'wf') {
                flowids.push(_keys[1])
            } else if (isShowNodeBtn && isNeedNode && _keys[0] == 'node') {
                nodeids.push(_keys[1])
            }
        }

        setSetting({checkedKeys: {checked: _checked, halfChecked: []}, typeids,flowids,nodeids});
    }

    getChildrenKeys(children) {
        const keys = [];
        for (let i = 0, len = children.length; i < len; i++) {
            const {key, props} = children[i];

            keys.push(key);
            if (props.children) {
                const keys = this.getChildrenKeys(props.children);
                keys.push(...keys);
            }
        }
        return keys;
    }

    onSelect = (selectedKeys, info)=>{
        console.info(selectedKeys, info)
    }

}